<template>
	<gradient-background>
		<view class="container">
			<view class="content">
				<!-- 头像编辑区域 -->
				<view class="avatar-section">
					<view class="avatar-container" @tap="showAvatarOptions">
						<user-avatar 
							:size="large"
							:userInfo="userInfo"
							:showUploadButton="true"
						></user-avatar>
						<view class="avatar-edit-hint">
							<text class="hint-text">点击更换头像</text>
						</view>
					</view>
				</view>
				
				<!-- 基本信息编辑 -->
				<app-card>
					<view class="form-section">
						<text class="section-title">基本信息</text>
						
						<view class="form-item">
							<text class="form-label">昵称</text>
							<input 
								v-model="userInfo.nickname" 
								placeholder="请输入昵称"
								class="form-input"
								maxlength="20"
							/>
						</view>
						
						<view class="form-item">
							<text class="form-label">性别</text>
							<view class="gender-selector">
								<view 
									class="gender-option" 
									:class="{ active: userInfo.gender === 1 }"
									@tap="selectGender(1)"
								>
									<text class="gender-text">男</text>
								</view>
								<view 
									class="gender-option" 
									:class="{ active: userInfo.gender === 2 }"
									@tap="selectGender(2)"
								>
									<text class="gender-text">女</text>
								</view>
								<view 
									class="gender-option" 
									:class="{ active: userInfo.gender === 0 }"
									@tap="selectGender(0)"
								>
									<text class="gender-text">保密</text>
								</view>
							</view>
						</view>
						
						<view class="form-item">
							<text class="form-label">出生日期</text>
							<picker 
								mode="date" 
								:value="userInfo.birthday" 
								@change="onBirthdayChange"
								class="form-picker"
							>
								<view class="picker-display">
									<text class="picker-text">{{ displayBirthday }}</text>
									<text class="picker-arrow">→</text>
								</view>
							</picker>
						</view>
						
						<view class="form-item">
							<text class="form-label">地区</text>
							<picker 
								mode="region" 
								:value="regionArray" 
								@change="onRegionChange"
								class="form-picker"
							>
								<view class="picker-display">
									<text class="picker-text">{{ displayRegion }}</text>
									<text class="picker-arrow">→</text>
								</view>
							</picker>
						</view>
						
						<view class="form-item">
							<text class="form-label">个人简介</text>
							<textarea 
								v-model="userInfo.bio" 
								placeholder="请输入个人简介..."
								class="form-textarea"
								maxlength="100"
							></textarea>
						</view>
					</view>
				</app-card>
				
				<!-- 联系方式 -->
				<app-card>
					<view class="form-section">
						<text class="section-title">联系方式</text>
						
						<view class="form-item">
							<text class="form-label">手机号</text>
							<view class="phone-display">
								<text class="phone-text">{{ displayPhone }}</text>
								<text class="bind-status" v-if="userInfo.phone">已绑定</text>
								<text class="bind-action" @tap="bindPhone" v-else>去绑定</text>
							</view>
						</view>
						
						<view class="form-item">
							<text class="form-label">微信</text>
							<view class="wechat-display">
								<text class="wechat-text">{{ displayWechat }}</text>
								<text class="bind-status" v-if="userInfo.wechatOpenId">已绑定</text>
								<text class="bind-action" @tap="bindWechat" v-else>去绑定</text>
							</view>
						</view>
					</view>
				</app-card>
				
				<!-- 占卜偏好设置 -->
				<app-card>
					<view class="form-section">
						<text class="section-title">占卜偏好</text>
						
						<view class="form-item">
							<text class="form-label">常用起卦方式</text>
							<view class="preference-selector">
								<view 
									class="preference-option" 
									:class="{ active: userInfo.preferredMethod === 'time' }"
									@tap="selectPreferredMethod('time')"
								>
									<text class="preference-text">时间起卦</text>
								</view>
								<view 
									class="preference-option" 
									:class="{ active: userInfo.preferredMethod === 'number' }"
									@tap="selectPreferredMethod('number')"
								>
									<text class="preference-text">数字起卦</text>
								</view>
							</view>
						</view>
						
						<view class="form-item">
							<view class="switch-item">
								<text class="switch-label">保存占卜记录</text>
								<switch 
									:checked="userInfo.saveRecords" 
									@change="onSaveRecordsChange"
									color="#6A82FB"
								/>
							</view>
						</view>
						
						<view class="form-item">
							<view class="switch-item">
								<text class="switch-label">接收推送通知</text>
								<switch 
									:checked="userInfo.enableNotification" 
									@change="onNotificationChange"
									color="#6A82FB"
								/>
							</view>
						</view>
					</view>
				</app-card>
				
				<!-- 保存按钮 -->
				<view class="action-section">
					<app-button 
						:text="'保存信息'" 
						type="primary"
						@tap="saveUserInfo"
						:loading="saving"
					></app-button>
				</view>
			</view>
		</view>
	</gradient-background>
</template>

<script>
import GradientBackground from '@/components/gradient-background/gradient-background.vue'
import AppCard from '@/components/app-card/app-card.vue'
import AppButton from '@/components/app-button/app-button.vue'
import UserAvatar from '@/components/user-avatar/user-avatar.vue'
import { LoginService } from '@/utils/login-service.js'

export default {
	name: 'UserInfoPage',
	components: {
		GradientBackground,
		AppCard,
		AppButton,
		UserAvatar
	},
	data() {
		return {
			userInfo: {
				nickname: '',
				gender: 0, // 0:保密, 1:男, 2:女
				birthday: '',
				region: '',
				bio: '',
				phone: '',
				wechatOpenId: '',
				avatar: '',
				preferredMethod: 'time',
				saveRecords: true,
				enableNotification: true
			},
			regionArray: ['广东省', '深圳市', '南山区'],
			saving: false,
			loginService: null
		}
	},
	computed: {
		displayBirthday() {
			return this.userInfo.birthday || '请选择出生日期'
		},
		
		displayRegion() {
			return this.userInfo.region || '请选择地区'
		},
		
		displayPhone() {
			if (this.userInfo.phone) {
				return this.userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
			}
			return '未绑定手机号'
		},
		
		displayWechat() {
			return this.userInfo.wechatOpenId ? '已绑定微信' : '未绑定微信'
		}
	},
	onLoad() {
		this.initData()
		this.loadUserInfo()
	},
	methods: {
		initData() {
			this.loginService = new LoginService()
		},
		
		loadUserInfo() {
			// 从本地存储加载用户信息
			uni.getStorage({
				key: 'user_info',
				success: (res) => {
					if (res.data) {
						this.userInfo = { ...this.userInfo, ...res.data }
						// 处理地区数组
						if (this.userInfo.region) {
							this.regionArray = this.userInfo.region.split(' ')
						}
					}
				},
				fail: () => {
					console.log('用户信息不存在，使用默认值')
				}
			})
		},
		
		showAvatarOptions() {
			uni.showActionSheet({
				itemList: ['拍照', '从相册选择'],
				success: (res) => {
					if (res.tapIndex === 0) {
						this.chooseImage('camera')
					} else if (res.tapIndex === 1) {
						this.chooseImage('album')
					}
				}
			})
		},
		
		chooseImage(sourceType) {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: [sourceType],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0]
					this.uploadAvatar(tempFilePath)
				},
				fail: (error) => {
					console.error('选择图片失败:', error)
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					})
				}
			})
		},
		
		uploadAvatar(filePath) {
			uni.showLoading({ title: '上传中...' })
			
			// 这里应该调用真实的上传接口
			// 暂时模拟上传过程
			setTimeout(() => {
				this.userInfo.avatar = filePath
				uni.hideLoading()
				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				})
			}, 1000)
		},
		
		selectGender(gender) {
			this.userInfo.gender = gender
		},
		
		onBirthdayChange(e) {
			this.userInfo.birthday = e.detail.value
		},
		
		onRegionChange(e) {
			this.regionArray = e.detail.value
			this.userInfo.region = e.detail.value.join(' ')
		},
		
		selectPreferredMethod(method) {
			this.userInfo.preferredMethod = method
		},
		
		onSaveRecordsChange(e) {
			this.userInfo.saveRecords = e.detail.value
		},
		
		onNotificationChange(e) {
			this.userInfo.enableNotification = e.detail.value
		},
		
		bindPhone() {
			uni.navigateTo({
				url: '/pages/login/login?type=phone'
			})
		},
		
		bindWechat() {
			this.loginService.wechatLogin()
				.then(result => {
					this.userInfo.wechatOpenId = result.openId
					uni.showToast({
						title: '微信绑定成功',
						icon: 'success'
					})
				})
				.catch(error => {
					console.error('微信绑定失败:', error)
					uni.showToast({
						title: '微信绑定失败',
						icon: 'none'
					})
				})
		},
		
		async saveUserInfo() {
			if (!this.userInfo.nickname) {
				uni.showToast({
					title: '请输入昵称',
					icon: 'none'
				})
				return
			}
			
			this.saving = true
			
			try {
				// 保存到本地存储
				uni.setStorage({
					key: 'user_info',
					data: this.userInfo
				})
				
				// 这里应该调用后端API保存用户信息
				// 暂时模拟保存过程
				await new Promise(resolve => setTimeout(resolve, 1000))
				
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
				
				// 延迟返回上一页
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
				
			} catch (error) {
				console.error('保存用户信息失败:', error)
				uni.showToast({
					title: '保存失败，请重试',
					icon: 'none'
				})
			} finally {
				this.saving = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	padding: 32rpx;
}

.content {
	padding-top: 40rpx;
}

.avatar-section {
	display: flex;
	justify-content: center;
	margin-bottom: 40rpx;
	
	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		
		.avatar-edit-hint {
			margin-top: 16rpx;
			
			.hint-text {
				font-size: 24rpx;
				color: rgba(0, 0, 0, 0.6);
			}
		}
	}
}

.form-section {
	.section-title {
		display: block;
		font-size: 32rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 32rpx;
	}
	
	.form-item {
		margin-bottom: 32rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.form-label {
			display: block;
			font-size: 28rpx;
			color: #000000;
			margin-bottom: 16rpx;
		}
		
		.form-input {
			width: 100%;
			height: 88rpx;
			padding: 0 24rpx;
			border: 2rpx solid #f0f0f0;
			border-radius: 12rpx;
			font-size: 28rpx;
			background-color: #fafafa;
		}
		
		.form-textarea {
			width: 100%;
			min-height: 120rpx;
			padding: 24rpx;
			border: 2rpx solid #f0f0f0;
			border-radius: 12rpx;
			font-size: 28rpx;
			line-height: 1.5;
			background-color: #fafafa;
		}
		
		.form-picker {
			.picker-display {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 88rpx;
				padding: 0 24rpx;
				border: 2rpx solid #f0f0f0;
				border-radius: 12rpx;
				background-color: #fafafa;
				
				.picker-text {
					font-size: 28rpx;
					color: #000000;
				}
				
				.picker-arrow {
					font-size: 24rpx;
					color: rgba(0, 0, 0, 0.6);
				}
			}
		}
	}
}

.gender-selector {
	display: flex;
	gap: 16rpx;
	
	.gender-option {
		flex: 1;
		height: 72rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 2rpx solid #f0f0f0;
		border-radius: 12rpx;
		background-color: #fafafa;
		transition: all 0.2s ease;
		
		&.active {
			border-color: #6A82FB;
			background-color: #6A82FB;
			
			.gender-text {
				color: white;
			}
		}
		
		.gender-text {
			font-size: 28rpx;
			color: #000000;
		}
	}
}

.preference-selector {
	display: flex;
	gap: 16rpx;
	
	.preference-option {
		flex: 1;
		height: 72rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 2rpx solid #f0f0f0;
		border-radius: 12rpx;
		background-color: #fafafa;
		transition: all 0.2s ease;
		
		&.active {
			border-color: #6A82FB;
			background-color: #6A82FB;
			
			.preference-text {
				color: white;
			}
		}
		
		.preference-text {
			font-size: 28rpx;
			color: #000000;
		}
	}
}

.phone-display,
.wechat-display {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 24rpx;
	border: 2rpx solid #f0f0f0;
	border-radius: 12rpx;
	background-color: #fafafa;
	
	.phone-text,
	.wechat-text {
		font-size: 28rpx;
		color: #000000;
	}
	
	.bind-status {
		font-size: 24rpx;
		color: #52C41A;
	}
	
	.bind-action {
		font-size: 24rpx;
		color: #6A82FB;
	}
}

.switch-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	
	.switch-label {
		font-size: 28rpx;
		color: #000000;
	}
}

.action-section {
	margin-top: 48rpx;
}
</style>